import time

from selenium.webdriver import Chrome
# 【2】驱动位置服务
from selenium.webdriver.chrome.service import Service
# 【3】选择器
from selenium.webdriver.common.by import By
# 【4】动作链
from selenium.webdriver import ActionChains

# 【二】创建浏览器对象
# 【1】指定驱动位置
executable_path = "./chromedriver.exe"
service = Service(
    executable_path=executable_path
)
# 【2】创建浏览器对象
browser = Chrome(
    service=service
)

# 【三】打开目标网址
browser.get("https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable")
time.sleep(3)

# 【四】完成拖拽动作
# 【1】创建动作链对象
actions = ActionChains(browser)

# 【2】定位元素

# （0）如果有 iframe 标签要切换到 iframe 标签内 再匹配
browser.switch_to.frame("iframeResult")

'''
# （1）起始位置
original_ele = browser.find_element(By.XPATH, '//*[@id="draggable"]')
# （2）定义结束位置
target_ele = browser.find_element(By.XPATH, '//*[@id="droppable"]')

actions.drag_and_drop(source=original_ele, target=target_ele).perform()

time.sleep(3)

'''
# （1）起始位置
original_ele = browser.find_element(By.XPATH, '//*[@id="draggable"]')
# （2）定义结束位置
target_ele = browser.find_element(By.XPATH, '//*[@id="droppable"]')
# （3）缓慢移动
'''
print(original_ele.location)
# {'x': 8, 'y': 8}
print(target_ele.location)
# {'x': 250, 'y': 0}
'''
distance = target_ele.location["x"] - original_ele.location["x"]

# 先要按住源标签
actions.click_and_hold(original_ele).perform()
# 我们移动的总长度
track = 0
per_track = 10
while track < distance:
    # 一点一点往后移动
    actions.move_by_offset(xoffset=per_track, yoffset=0).perform()
    print(f"起始距离 {track} 每次移动 {per_track} 已经移动 {track}")
    track += per_track

# 移动到指定为止之后 应该松开我们源标签
actions.release().perform()
time.sleep(5)
